/*
 *
 *
 */

package betAndWin.sound;



import java.io.File;
import java.io.IOException;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {
	private Sequencer soundMidi;
	private Clip soundWav;
	private int checkType=-1;
	private static final int SOUNDMIDI=0;
	private static final int SOUNDWAV=1;

	public Sound(){}

	public Sequencer getSoundMidi()throws NotValidValueException{
		if(this.checkType!=Sound.SOUNDMIDI)
			throw new NotValidValueException();
		return this.soundMidi;
	}

	public Clip getSoundWav() throws NotValidValueException{
		if(this.checkType!=Sound.SOUNDWAV)
			throw new NotValidValueException();
		return this.soundWav;
	}

	public Sequencer loadMidi(String pAddress) throws NotValidValueException{
		Sequence sequence;
		Sequencer sequencer=null;

		this.analizeType(pAddress);
		if(checkType!=Sound.SOUNDMIDI) throw new NotValidValueException();

		try {
			sequence = MidiSystem.getSequence(new File(pAddress));

			// Create a sequencer for the sequence
			sequencer = MidiSystem.getSequencer();
			sequencer.open();
			sequencer.setSequence(sequence);
			// Start playing
			sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
		} catch (IOException ex) {}
		catch (InvalidMidiDataException ex) {}
		catch (MidiUnavailableException ex) {}
		return sequencer;
	}

	public Clip loadWav(String pAddress) throws NotValidValueException{
		File sf;
		AudioFileFormat aff;
		AudioInputStream ais;
		Clip sound = null;

		this.analizeType(pAddress);
		if(checkType!=Sound.SOUNDWAV) throw new NotValidValueException();

		try {
			sf = new File(pAddress);
			aff = AudioSystem.getAudioFileFormat(sf);
			ais = AudioSystem.getAudioInputStream(sf);
			AudioFormat af = aff.getFormat();
			DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat(), (int) ais.getFrameLength() * af.getFrameSize());
			sound = (Clip) AudioSystem.getLine(info);
			sound.open(ais);
		} catch (UnsupportedAudioFileException ex) {}
		catch (IOException ex) {}
		catch (LineUnavailableException ln){}
		return sound;
	}

	private void analizeType(String pAnalized){
		char lastWord[]=new char[3];
		for(int i=0; i<3;i++){
			lastWord[i]=pAnalized.charAt(pAnalized.length()-(3-i));
		}
		if((lastWord[0]=='m')&&(lastWord[1]=='i')&&(lastWord[2]=='d'))
			this.checkType=Sound.SOUNDMIDI;
		else if((lastWord[0]=='w')&&(lastWord[1]=='a')&&(lastWord[2]=='v'))
			this.checkType=Sound.SOUNDWAV;
		else this.checkType=-1;
	}
}